package com.citycloud.ccuap.tc.sync.aspect;

import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.commons.sys.project.IProjectService;
import com.citycloud.ccuap.tc.sync.dto.UserMessageDTO;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncOperation;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.dto.SyncDataDto;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zjl
 * @date 2020/04/30 9:58
 */
@Aspect
@Component
public class UserAddAspect {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IProjectService projectService;

    @Pointcut("execution(* com.citycloud.ccuap.commons.sys.user.UserController.add())")
    public void add() {
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @AfterReturning(value = "add()", returning = "key")
    public void add(JoinPoint joinPoint, Object key) throws Throwable {
        if (key instanceof JSONData) {
            JSONData jsonData = (JSONData) key;
            if (jsonData.getData() instanceof SysUser) {
                SysUser user = (SysUser) jsonData.getData();
                if (user.getProjectId() != null) {
                    // 移除敏感信息
                    user.setPassword(null);
                    user.setDesPassword(null);

                    SysProject project = projectService.findById(user.getProjectId());
                    if (project != null && project.getMqOff()) {
                        UserMessageDTO userMessageDTO = new UserMessageDTO();
                        userMessageDTO.build(user);

                        sendJmsMessage(user.getProjectId(), userMessageDTO);
                    }
                }
            }
        }

    }

    private void sendJmsMessage(Long projectId, UserMessageDTO dto) {
        SyncDataDto<UserMessageDTO> result = SyncDataDto.of(GlobalSyncType.OBJECT_TYPE_USER,
                GlobalSyncOperation.CREATED, projectId, dto);
        messageService.sendMessageByTopic(result,GlobalSyncType.TOPIC_USER_DEPT);
    }

}
